package com.peng.community.controller;

import com.google.code.kaptcha.Producer;
import com.peng.community.annotation.LoginRequire;
import com.peng.community.constant.CommunityConstant;
import com.peng.community.entity.User;
import com.peng.community.service.LoginTicketService;
import com.peng.community.service.UserService;
import com.peng.community.util.CommunityUtils;
import com.peng.community.util.RedisKeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
@Slf4j
public class LoginController implements CommunityConstant {

    @GetMapping("/site/register")
    public String getRegisterPage() {
        return "/site/register";
    }

    @Autowired
    UserService userService;

    @PostMapping("/register")
    public String register(Model model, User user) {
        Map<String, Object> register = userService.register(user);
        System.out.println("正在注册" + user);
        System.out.println("注册结果" + register);
        if (register == null || register.isEmpty()) {
            //注册成功，跳转
            model.addAttribute("msg","激活邮件已经发送，请激活");
            model.addAttribute("url","/index");
            return "/site/operate-result";
        } else {
            model.addAttribute("usernameError",register.get("usernameError"));
            model.addAttribute("emailError",register.get("emailError"));
            model.addAttribute("passwordError",register.get("passwordError"));
            model.addAttribute("user",user);
            return "/site/register";
        }
    }

    @GetMapping("test")
    public String test() {
        return "/site/operate-result";
    }

    @GetMapping("/activation/{userId}/{code}")
    public String activate(Model model, @PathVariable("userId") int userId, @PathVariable("code") String code) {
        int result = userService.activate(userId, code);
        if (result == ACTIVATE_SUCCESS) {
            //激活成功，跳转
            model.addAttribute("msg","激活成功，请登录");
            model.addAttribute("url","/login");
            return "/site/operate-result";
        } else if (result == ACTIVATE_REPEATED) {
            model.addAttribute("msg","无效操作，该账号已经激活");
            model.addAttribute("url","/index");
            return "/site/operate-result";
        } else {
            model.addAttribute("msg","激活失败！");
            model.addAttribute("url","/site/register");
            return "/site/operate-result";
        }
    }

    @GetMapping("/login")
    public String getLoginPage() {
        return "/site/login";
    }


    @Autowired
    Producer kaptchaProducer;

    @Autowired
    RedisTemplate redisTemplate;

    @GetMapping("/kaptcha")
    public void getKaptcha(HttpServletResponse response/*, HttpSession session*/) {
        String text = kaptchaProducer.createText();

        //session.setAttribute("kaptcha",text);
        //重构，将验证码放入redis

        //1.生成一个临时用户凭证，通过cookie响应给用户
        String kaptchaOwner = CommunityUtils.getUUID();
        Cookie cookie = new Cookie("kaptchaOwner", kaptchaOwner);
        cookie.setPath(contextPath);
        cookie.setMaxAge(60);//60s存活时间
        response.addCookie(cookie);
        String kaptchaKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
        //将验证码存入redis
        redisTemplate.opsForValue().set(kaptchaKey, text,60, TimeUnit.SECONDS);

        BufferedImage image = kaptchaProducer.createImage(text);
        response.setContentType("img/png");
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(image,"png",outputStream);
        } catch (IOException e) {
            log.error("图片传输错误");
        }
    }

    @Value("${server.servlet.context-path}")
    public String contextPath;

    @Autowired
    LoginTicketService loginTicketService;


    @PostMapping("/login")
    //tick 是否勾选“记住我”
    public String login(String username, String password, String kaptcha, boolean tick,
         @CookieValue("kaptchaOwner") String kaptchaOwner, /*HttpSession session, */HttpServletResponse response, Model model) {
        //首先判断激活码（无需查询数据库）
//        String code = (String) session.getAttribute("kaptcha");

        //重构：从redis获取验证码
        String code = null;
        if (StringUtils.isNotBlank(kaptchaOwner)) {
            String kaptchaKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
            code = (String) redisTemplate.opsForValue().get(kaptchaKey);
        }

        if (StringUtils.isBlank(kaptcha) || StringUtils.isBlank(code) ||
                !kaptcha.equalsIgnoreCase(code)) {
            model.addAttribute("codeError", "验证码错误");
            return "/site/login";
        }
        int expireTime = tick ? EXTRA_EXPIRE_TIME : DEFAULT_EXPIRE_TIME;
        Map<String, Object> loginResult = loginTicketService.login(username, password, expireTime);
        if (loginResult.containsKey("ticket")) {
            //登录成功
            Cookie cookie = new Cookie("ticket", loginResult.get("ticket").toString());
            cookie.setPath(contextPath);
            cookie.setMaxAge(expireTime);

            //别忘了吧cookie加入响应头
            response.addCookie(cookie);
            return "redirect:/index";
        } else {
            //登录失败
            model.addAttribute("usernameError", loginResult.get("usernameError"));
            model.addAttribute("passwordError", loginResult.get("passwordError"));
            return "/site/login";
        }


    }

    @LoginRequire
    @GetMapping("/layout")
    public String layout(@CookieValue("ticket")String ticket) {
        loginTicketService.layout(ticket);
//        SecurityContextHolder.clearContext();
        return "redirect:/login";
    }
}
